﻿using OnlineEducation.Helpers;
using Microsoft.AspNetCore.Http;
using Serilog;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OnlineEducation.Extensions
{
    public static class EnricherExtensions
    {
        public static LoggerConfiguration WithRequestInfo(this LoggerEnrichmentConfiguration enrich)
        {
            if (enrich == null)
                throw new ArgumentNullException(nameof(enrich));

            return enrich.With<RequestInfoEnricher>();
        }
    }
    public class RequestInfoEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var httpContext = HttpContextHelper.Current;
            if (null != httpContext)
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserID", httpContext?.User.Identity.Name));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestIP", httpContext?.Connection.RemoteIpAddress.MapToIPv4().ToString()));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestPath", httpContext?.Request.Path));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Referer", httpContext?.Request.Headers["Referer"]));
            }
        }
    }

}
